<template>
  <!-- <div id="container"></div> -->
  <div class="lsh-box">
    <div class="lsh-canvas" id="container" :style="{ position: 'absolute' }">
      <!-- <div class="lsh-tool-list">
        <button class="lsh-pen-btn" @click="startPen = !startPen">
          {{ startPen ? '关闭' : '开启' }}画笔
        </button>
        <button class="lsh-pen-btn" @click="clear()">
          清除
        </button>
      </div> -->
    </div>
    <div class="lsh-page">
      背景内容
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted } from 'vue';
import Konva from 'konva';

const containerRef = ref<HTMLElement | null>(null);
let stage: Konva.Stage | null = null;
let layer: Konva.Layer | null = null;
let isPaint = false;
let mode = 'brush';
let lastLine: Konva.Line | null = null;

onMounted(() => {
  const width = window.innerWidth;
  const height = window.innerHeight - 25;

  stage = new Konva.Stage({
    container: 'container',
    width,
    height
  });

  layer = new Konva.Layer();
  stage.add(layer);

  stage.on('mousedown touchstart', handleMouseDown);
  stage.on('mouseup touchend', handleMouseUp);
  stage.on('mousemove touchmove', handleMouseMove);
});

const handleMouseDown = (e: Konva.KonvaEventObject<MouseEvent | TouchEvent>) => {
  e.evt.preventDefault(); // 阻止默认事件
  isPaint = true;
  const pos = stage?.getPointerPosition();
  if (!pos) return;

  lastLine = new Konva.Line({
    stroke: 'rgb(50,205,121)'||'#df4b26',
    strokeWidth: 5,
    globalCompositeOperation: mode === 'brush' ? 'source-over' : 'destination-out',
    points: [pos.x, pos.y]
  });
  layer?.add(lastLine);
};

const handleMouseUp = () => {
  isPaint = false;
};

const handleMouseMove = (e: Konva.KonvaEventObject<MouseEvent | TouchEvent>) => {
  e.evt.preventDefault(); // 阻止默认事件
  if (!isPaint || !lastLine || !stage) return;

  const pos = stage.getPointerPosition();
  if (!pos) return;

  const newPoints = lastLine.points().concat([pos.x, pos.y]);
  lastLine.points(newPoints);
  layer?.batchDraw();
};
const clear = () => {
  console.log(layer)
};
</script>

<style scoped lang='less'>
.lsh-box {
  position: relative;
  width: 100vw;
  height: 100vh;

  .lsh-canvas {
    width: 100vw;
    height: 100vh;
    position: absolute;
    z-index: 9999;
    background-color: transparent;
    padding: 20px;

    .lsh-tool-list {
      position: absolute;
      display: flex;
      gap: 20px;
      z-index: 1;

      .lsh-pen-btn {
        cursor: pointer;
      }
    }
  }

  .lsh-page {
    width: 100%;
    height: 100%;
    background-color: #c2650e;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>